package 算法.LeetCode91.每日打卡题目;

import 算法.NiuKe.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author: 谢君臣
 * @create: 2021-02-17 10:02
 * @founction: XXXX
 */
public class day17 {
    public static void main(String[] args) {
        TreeNode treeNode = deserialize("[1,2,2]");
        String s = serialize(treeNode);
        System.out.println(s);
    }
    // Encodes a tree to a single string.
    public static String serialize(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            if (node!=null){
                list.add(node.val);
                queue.add(node.left);
                queue.add(node.right);
            }else {
                list.add(null);
            }
        }
        while (list.size()>0&&list.get(list.size()-1)==null)
            list.remove(list.size()-1);
        return list.toString();
    }

    // Decodes your encoded data to tree.
    public static TreeNode deserialize(String data) {
        if (data.length()<=2)
            return null;
        Queue<TreeNode> queue = new LinkedList<>();
        String s = data.substring(1, data.length() - 1);
        String[] split = s.split(",");
        TreeNode root ;
        if (split.length>=1&&!split[0].equals("null"))
            root = new TreeNode(Integer.parseInt(split[0]));
        else
            return null;
        queue.add(root);
        for (int i = 0; i < split.length/2; i++) {
            TreeNode node = queue.poll();
            try {
                node.left = createNode(split[i*2+1]);
            }catch (Exception e){
                node.left = null;
            }
            try {
                node.right = createNode(split[i*2+2]);
            }catch (Exception e){
                node.right = null;
            }
            if (node.left!=null)
                queue.add(node.left);
            if (node.right!=null)
                queue.add(node.right);
        }
        return root;
    }

    public static TreeNode createNode(String s) {
        if (s.equals("null")||s.equals(""))
            return null;
        else
            return new TreeNode(Integer.parseInt(s.trim()));
    }
}
